<template>
    <div>
        <el-form label-width="100px">
            <el-form-item label="SPU名称">
                <el-input aria-placeholder="输入SPU名称" v-model="spuParams.spuName"></el-input>
            </el-form-item>
            <el-form-item label="SPU品牌">
                <el-select style="width: 280px;" v-model="spuParams.tmId">
                    <el-option v-for="(item, index) in AllTradeMark" :key="item.id" :label="item.tmName"
                        :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="SPU描述">
                <el-input type="textarea" aria-placeholder="输入SPU描述" v-model="spuParams.description"></el-input>
            </el-form-item>
            <el-form-item label="SPU图标">
                <el-upload v-model:file-list="ImageList" action="/api//admin/product/fileUpload"
                    list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                    <el-icon>
                        <Plus />
                    </el-icon>
                </el-upload>
                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" width="100%" height="100%" />
                </el-dialog>
            </el-form-item>
            <el-form-item label="SPU销售属性">
                <el-select style="width: 180px;" v-model="saleAttrIdAndValueName"
                    :placeholder="unSelectSaleAttr.length ? `还有${unSelectSaleAttr.length}个可选` : '暂无选择'">
                    <el-option v-for="(item, index) in unSelectSaleAttr" :key="item.id" :label="item.name"
                        :value="`${item.id}:${item.name}`"></el-option>
                </el-select>
                <el-button :disabled="saleAttrIdAndValueName ? false : true" style="margin-left: 10px;" type="primary"
                    icon="Plus" @click="addSaleAttr">添加属性</el-button>

                <el-table style="margin: 10px 0;" border :data="SaleAttrList">
                    <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>
                    <el-table-column label="销售属性名字" width="120px" prop="saleAttrName"></el-table-column>
                    <el-table-column label="销售属性值">
                        <template #="{ row, $index }">
                            <el-tag v-for="(item, index) in row.spuSaleAttrValueList" :key="item.id"
                                style="margin: 5px;" @close="row.spuSaleAttrValueList.splice(index, 1)" closable>{{
                    item.saleAttrValueName }}</el-tag>
                            <el-input v-if="row.flag == true" v-model="row.saleAttrValue" style="width:100px"
                                @blur="toLook(row)"></el-input>
                            <el-button v-else type="primary" icon="Plus" @click="toEdit(row)"></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template #="{ row, $index }">
                            <el-button type="Info" icon="Delete" @click="SaleAttrList.splice($index, 1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="save">保存</el-button>
                <el-button @click="cancel">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup lang='ts'>
import { reqAllTradeMark, reqSpuInfo, reqAllSaleAttr, reqAddOrUpdate } from '@/api/product/spu'
import { ElMessage } from 'element-plus';
import { ref, computed } from 'vue'
const emit = defineEmits(['changeScene'])
const AllTradeMark = ref([])
const ImageList = ref([])
const SaleAttrList = ref([])
const AllSaleAttr = ref([])
const spuParams = ref({
    category3Id: "",
    spuName: "",
    description: "",
    tmId: "",
    spuImageList: [],
    spuSaleAttrList: []
})
const dialogVisible = ref(false)
const dialogImageUrl = ref()

const saleAttrIdAndValueName = ref('')
const cancel = () => {
    emit('changeScene', 0)
}

const initHasSpuData = async (spu) => {
    spuParams.value = spu
    const res = await reqAllTradeMark()
    const InfoList = await reqSpuInfo(spu.id)
    ImageList.value = InfoList.data.spuImageList.map(item => {
        return {
            name: item.imgName,
            url: item.imgUrl
        }
    })
    SaleAttrList.value = InfoList.data.spuSaleAttrList
    const allAttr = await reqAllSaleAttr()

    AllTradeMark.value = res.data
    AllSaleAttr.value = allAttr.data
    // console.log(ImageList.value)
    // console.log(ImageList.value,SaleAttrList.value ,AllTradeMark.value,AllSaleAttr.value)

}


const handlePictureCardPreview = (file) => {
    dialogVisible.value = true
    dialogImageUrl.value = file.url
}

const handleRemove = () => { }

const unSelectSaleAttr = computed(() => {
    const unSelectAttr = AllSaleAttr.value.filter(item => {
        return SaleAttrList.value.every(item1 => {
            return item.name != item1.saleAttrName
        })
    })
    return unSelectAttr
})

const addSaleAttr = () => {
    const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
    const newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: []
    }
    SaleAttrList.value.push(newSaleAttr)
    // console.log(SaleAttrList.value)
    saleAttrIdAndValueName.value = ''
}

const toEdit = (row) => {
    row.flag = true
    row.saleAttrValue = ""
}

const toLook = (row) => {
    const { baseSaleAttrId, saleAttrValue } = row
    const newSaleAttrValue = {
        baseSaleAttrId,
        saleAttrValueName: saleAttrValue
    }
    if (saleAttrValue.trim() == '') {
        ElMessage({
            type: 'error',
            message: '属性不能为空'
        })
        return
    }
    let repeat = row.spuSaleAttrValueList.find(item => {
        return item.saleAttrValueName == saleAttrValue
    })
    if (repeat) {
        ElMessage({
            type: 'error',
            message: '属性重复'
        })
        return
    }

    row.spuSaleAttrValueList.push(newSaleAttrValue)
    row.flag = false
}

const save = async () => {
    spuParams.value.spuImageList = ImageList.value.map(item => {
        return {
            imgName: item.name,
            imgUrl: (item.response && item.response.data) || item.url
        }
    })
    spuParams.value.spuSaleAttrList = SaleAttrList.value
    const res = await reqAddOrUpdate(spuParams.value)
    console.log(res)
    if (res.code == 200) {
        ElMessage({
            type: 'success',
            message: spuParams.value.id ? '更新成功' : '添加成功'
        })
        emit('changeScene', 0)
    } else {
        ElMessage({
            type: 'error',
            message: '失败'
        })
    }
}

const initAddSpu = async (C3Id) => {
    Object.assign(spuParams, {
        category3Id: "",
        spuName: "",
        description: "",
        tmId: "",
        spuImageList: [],
        spuSaleAttrList: []
    })
    ImageList.value = []
    SaleAttrList.value = []
    saleAttrIdAndValueName.value=''
    spuParams.value.category3Id = C3Id
    const res = await reqAllTradeMark()
    const allAttr = await reqAllSaleAttr()

    AllTradeMark.value = res.data
    AllSaleAttr.value = allAttr.data
}
defineExpose({ initHasSpuData, initAddSpu })
</script>

<style scoped></style>